package com.isoft.permanprovidor.service.sgman;

import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.isoft.permanprovidor.bean.ResponseData;
import com.isoft.permanprovidor.bean.ResultCode;
import com.isoft.permanprovidor.bean.SysUser;
import com.isoft.permanprovidor.dao.sgman.ExterPerson_Dao;
import com.isoft.permanprovidor.entity.sgman.ContractWorker;
import com.isoft.permanprovidor.entity.sgman.ExterPerson;
import com.isoft.permanprovidor.unit.IdUtil;
import com.isoft.permanprovidor.unit.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
@Slf4j
public class ExterPerson_Service {
    @Autowired
    ExterPerson_Dao exterPerson_dao;
    @Autowired
    RestTemplate restTemplate;

    final String baseUri = "http://uaa/sys/user/";

    /*分页综合查询操作*/
    public ResponseData PageSynthSelect(Integer currentPage ,Integer size,String name){
        Page<ExterPerson> page = new Page<>();
        // 初始化分页参数
        if (currentPage == null || currentPage < 1){
            currentPage = 1;
        }
        if (size == null || size < 1){
            size =10;
        }

        // 构建查询条件
        page.setCurrent(currentPage).setSize(size);
        QueryWrapper wrapper = new QueryWrapper();
        //通过搜索姓名模糊查询
        if (!name.isEmpty()){
            wrapper.like("name" , name);
        }

        wrapper.orderByAsc("id");

        //构造返回Controller 的结果
        ResponseData responseData = new ResponseData();
        responseData.setErrorCode(ResultCode.SUCCESS.getCode());
        responseData.setMsg(ResultCode.SUCCESS.getMessage());
        responseData.setData(exterPerson_dao.selectPage(page , wrapper));
        return responseData;
    }

    /*新增外聘人员*/
    public Boolean add(ExterPerson exterPerson){
        boolean result = false;
        if (exterPerson.getName().isEmpty()||exterPerson.getIdcard().isEmpty()) {
            return result;
        }
        try {
            // 获取身份证后六位作为默认密码
            String idcard = exterPerson.getIdcard();
            String password = idcard.substring(idcard.length() - 6);
            System.out.println("身份证后六位:" + password);



            // 创建Sysuser参数
            SysUser sysUser = new SysUser();
            sysUser.setUsername(exterPerson.getSysuserid());
            sysUser.setPassword(password);

            log.info("远程调用uaa的registerresttemplate接口");
            // 远程调用注册接口
            Boolean response = restTemplate.postForObject(baseUri + "registerresttemplate", sysUser, Boolean.class);

            // 检查远程调用结果，根据需要更新结果
            if (response != null || response) {
                log.info("远程调用 uaa 的 registerresttemplate 接口，成功");
                // 尝试插入合同工
                exterPerson_dao.insert(exterPerson);
                result = true;
            } else {
                log.warn("远程调用 uaa 的 registerresttemplate 接口，失败");
            }
        } catch (Exception e) {
            log.error("添加外聘人员或远程注册出错", e);
            // 抛出异常
            throw new RuntimeException("添加外聘人员或远程注册出错", e);
        }
        return result;
    }

    /*EXCEL文件批量导入外聘人员信息*/
    public boolean bulkImport(String fileUrl){
        if (StringUtil.isEmpty(fileUrl)) {
            log.warn("文件路径为空");
            return false;
        }
        log.info("开始读取文件: {}", fileUrl);
        // 写法1：JDK8+ ,不用额外写一个DemoDataListener
        // since: 3.0.0-beta1
        try {
            // 使用 EasyExcel 读取文件
            // 这里默认每次会读取100条数据 然后返回过来 直接调用使用数据就行
            // 具体需要返回多少行可以在`PageReadListener`的构造函数设置
            com.alibaba.excel.EasyExcel.read(fileUrl, ExterPerson.class, new PageReadListener<ExterPerson>(dataList -> {
                for (ExterPerson exterPerson : dataList) {
                    log.info("读取到一条数据: {}", JSON.toJSONString(exterPerson));
                    // 持久化操作
                    boolean added = add(exterPerson);
                    if (!added) {
                        log.warn("合同工 {} 添加失败", exterPerson.getName());
                    }
                }
            })).sheet().doRead();
        } catch (Exception e) {
            log.error("批量导入合同工信息时出错", e);
            return false;
        }
        return true;
    }

    /*修改外聘人员信息*/
    public Boolean update(ExterPerson exterPerson){
        if (exterPerson == null || !IdUtil.idCheck(exterPerson.getId())) {
            log.warn("外聘人员信息为空或 ID 无效");
            return false;
        }
        try {
            int updateCount = exterPerson_dao.updateById(exterPerson);
            if (updateCount > 0) {
                log.info("外聘人员信息更新成功，ID: {}", exterPerson.getId());
                return true;
            } else {
                log.warn("外聘人员信息更新失败，ID: {}", exterPerson.getId());
                return false;
            }
        } catch (Exception e) {
            log.error("更新外聘人员信息时出错，ID: {}", exterPerson.getId(), e);
            throw new RuntimeException("更新外聘人员信息时出错", e);
        }
    }

    /*启/停用该合同工*/
    public Boolean islock(Integer id ,String sysuserid,Integer islock){
        boolean result = false;
        // 参数校验：确保 id 和 sysuserid 不能为空，islock 也不能为 null
        if (id == null || sysuserid.isEmpty() || islock == null) {
            log.warn("参数无效，id: {}, sysuserid: {}, islock: {}", id, sysuserid, islock);
            return result;
        }
        try {
            ExterPerson exterPerson = new ExterPerson();
            exterPerson.setIslock(islock);

            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("id" , id);
            wrapper.eq("sysuserid" , sysuserid);


            // 创建Sysuser参数

            SysUser sysUser = new SysUser();
            sysUser.setUsername(sysuserid);
            sysUser.setIslock(islock);
            //System.out.println(sysUser);

            log.info("远程调用uaa的freezeenable接口");
            // 远程调用接口
            Boolean response = restTemplate.postForObject(baseUri + "freezeenable", sysUser, Boolean.class);
            // 检查远程调用结果，根据需要更新结果
            if (response != null && response) {
                log.info("远程调用 uaa 的 freezeenable 接口，成功");

                // 执行更新操作
                exterPerson_dao.update(exterPerson, wrapper);
                result = true;

            } else {
                log.warn("远程调用 uaa 的 freezeenable 接口，失败");
                return result;
            }
        }catch (Exception e) {
            log.error("停用或远程冻结出错", e);
            // 抛出异常
            throw new RuntimeException("停用或远程冻结出错", e);
        }
        return result;
    }


}
